package com.file.parser;

import com.file.bo.CCB;
import com.file.bo.CCBTran;
import com.file.bo.ResponseData;
import com.file.constant.ErrorCode;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
public class CCBExcelParser {

	public ResponseData<String> parseCCBExcelToJson(String daId,String filePath) {
		log.info("parseCCBExcelToJson started, daId:{}", daId);
		String json = null;

		try {
			CCB ccb = parseCCBExcel(filePath);
			json = JsonUtils.convertObjectToJson(ccb);
			doAlert(daId, ccb);
		} catch (Exception e) {
			log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseCCBExcelToJson failed", e);
			return new ResponseData<String>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(), ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
		}

		log.info("parseCCBExcelToJson completed, daId:{}", daId);
		return new ResponseData<String>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
	}

	public CCB parseCCBExcel(String filePath) {
		CCB ccb = null;
		try (FileInputStream fis = new FileInputStream(new File(filePath));
			 HSSFWorkbook workbook = new HSSFWorkbook(fis)) {
			HSSFSheet sheet = workbook.getSheetAt(0);
			ccb = new CCB();
			List<CCBTran> ccbTrans = new ArrayList<CCBTran>();
			for (int i = 0; i < sheet.getLastRowNum(); i++) {
				Row row = sheet.getRow(i);
				if (i == 1) {
					ccb.setAccountOpeningInstitution(row.getCell(1).getStringCellValue());
				}
				if (i == 2) {
					ccb.setCurrency(row.getCell(1).getStringCellValue());
				}
				if (i == 3) {
					ccb.setAccountNumber(row.getCell(1).getStringCellValue());
				}

				if (i >= 6) {
					CCBTran ccbTran = new CCBTran();
					ccbTran.setBookkeepingDate(row.getCell(0).getStringCellValue());
					ccbTran.setTransactionDate(row.getCell(1).getStringCellValue());
					ccbTran.setTransactionTime(row.getCell(2).getStringCellValue());
					ccbTran.setExpense(this.getStringCellValue(row.getCell(3)));
					ccbTran.setRevenue(this.getStringCellValue(row.getCell(4)));
					ccbTran.setAccountbalance(this.getStringCellValue(row.getCell(5)));
					ccbTran.setCurrency(row.getCell(6).getStringCellValue());
					ccbTran.setSummary(row.getCell(7).getStringCellValue());
					ccbTran.setCounterPartyAccountNumber(row.getCell(8).getStringCellValue());
					ccbTran.setCounterPartyAccountName(row.getCell(9).getStringCellValue());
					ccbTran.setTradingPlace(row.getCell(10).getStringCellValue());
					ccbTrans.add(ccbTran);
				}
			}
			ccb.setCcbTrans(ccbTrans);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		return ccb;
	}

	private void doAlert(String daId, CCB ccb) {
		log.info("doAlert started daId: {}", daId);

		//加入字段告警
		if (StringUtils.isBlank(ccb.getAccountOpeningInstitution())) {
			log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseCCBExcelToJson ccb AccountOpeningInstitution is null");
			throw new RuntimeException();
		}

		//加入字段告警
		if (StringUtils.isBlank(ccb.getCurrency())) {
			log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseCCBExcelToJson ccb Currency is null");
			throw new RuntimeException();
		}

		if (StringUtils.isBlank(ccb.getAccountNumber())) {
			log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseCCBExcelToJson ccb AccountNumber is null");
			throw new RuntimeException();
		}

		List<CCBTran> ccbTrans = ccb.getCcbTrans();
		if (ccbTrans.size() == 0) {
			log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseCCBExcelToJson ccbTrans size is 0");
		}

		for (CCBTran ccbTran : ccbTrans) {
			if (StringUtils.isBlank(ccbTran.getBookkeepingDate())) {
				log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseCCBExcelToJson ccbTran BookkeepingDate is null");
				throw new RuntimeException();
			}
			if (StringUtils.isBlank(ccbTran.getTransactionDate())) {
				log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseCCBExcelToJson ccbTran TransactionDate is null");
				throw new RuntimeException();
			}
			if (StringUtils.isBlank(ccbTran.getTransactionTime())) {
				log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseCCBExcelToJson ccbTran TransactionTime is null");
				throw new RuntimeException();
			}
			if (StringUtils.isBlank(ccbTran.getExpense())) {
				log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseCCBExcelToJson ccbTran Expense is null");
				throw new RuntimeException();
			}
			if (StringUtils.isBlank(ccbTran.getRevenue())) {
				log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseCCBExcelToJson ccbTran Revenue is null");
				throw new RuntimeException();
			}
			if (StringUtils.isBlank(ccbTran.getAccountbalance())) {
				log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_NULL_ALERT_EXCEPTION.getCode(), daId, "", "", "parseCCBExcelToJson ccbTran Accountbalance is null");
				throw new RuntimeException();
			}
		}

		log.info("doAlert completed daId: {}", daId);
	}

	private String getStringCellValue(Cell cell) {
		String cellStr;
		if (Objects.equals(cell.getCellType(), CellType.NUMERIC)) {
			cellStr = String.valueOf(cell.getNumericCellValue());
		} else {
			cellStr = cell.getStringCellValue();
		}
		return cellStr;
	}

	public static void main(String[] args) throws IOException {
		String pdfFilePath = "D:\\data\\file\\建设银行.xls";
//        String jsonFilePath = "D:\\data\\file\\建设银行.json";
//        File jsonFile = new File(jsonFilePath);

		CCBExcelParser ccbExcelParser = new CCBExcelParser();
		ResponseData<String> responseData = ccbExcelParser.parseCCBExcelToJson("dd", pdfFilePath);
		System.out.println(responseData.getData());
//        FileUtils.write(jsonFile, responseData.getData(), "UTF-8");
//        jsonFile.createNewFile();
	}

}
